import React, { Component } from 'react';
import {
    View,
    Image,
    TextInput,
    ScrollView,
    StyleSheet,
    DeviceEventEmitter
} from 'react-native'

import KeyEvent from 'react-native-keyevent'
import moment from 'moment';
import Toast from 'react-native-root-toast';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { updatePurchaseList } from '../../actions/PurchaseAction';

import * as fetch from '../../utils/fetch'
import o from '../../components/o'
import Style from '../../utils/style/style'
import Loading from '../../views/loading';
import CellItem from '../../views/cellItem';
import CheckStateItem from '../../views/checkStateItem';
import CellTitleItem from '../../views/cellTitleItem';
import SerialsItem from '../../views/serialsItem';
import GoodItem from '../../views/goodItem';
import IconCellItem from '../../views/iconCellItem';
import QrCode from '../../views/qrCode';
import PrimaryButton from '../../views/primaryButton';
import MsgModal from '../../components/modal/errorModal';
import ConfirmModal from '../../components/modal/confirmModal';
import RfidModule from '../../components/Rfid'
class WareHouse extends Component {
    constructor(props) {
        super(props)
        this.state = {
            PurchaseId: '',
            RecId: '',
            gooodsItem: null,
            disable: false,
            codesStr: '',
            codesArr: [],
            // codesArr: ['00011FFF000001AAAA000998'],
            // codesStr: '00011FFF000001AAAA000998',
            dataList: [],
            modal: {
                title: '',
                msg: '',
                visible: false
            },
            confirmModal: {
                title: '',
                msg: '',
                visible: false,
                confirmFuc: () => null,
            },
            operaDisable: false,
            repeatCodes: [],
        }
    }
    static navigationOptions = {
        title: '商品入库情况'
    }
    componentWillMount() {
        //通过使用DeviceEventEmitter模块来监听原生模块发送过来的事件
        DeviceEventEmitter.addListener('onInventoryTag', (Event) => {
            //盘存标签触发回调
            let result = Event.RfidResult;
            let codesArr = this.state.codesArr;
            for (let i = 0; i < codesArr.length; i++) {
                if (codesArr[i] == result) {
                    return;
                }
            }
            codesArr.push(result);
            this.setState({
                codesArr: codesArr,
            })
        });
        DeviceEventEmitter.addListener('onInventoryTagEnd', (Event) => {
            //盘存结束回调  
            const { codesArr } = this.state;
            if (codesArr.length > 20) {
                this._showModal("失败", "批量扫描个数请控制在20个以内");
                this.setState({
                    codesArr: [],
                    codesStr: '',
                })
            } else {
                this.setState({
                    codesStr: codesArr.join(',')
                })
            }

        });
        DeviceEventEmitter.addListener('onExeCMDStatus', (Event) => {
            this._showModal("失败", Event.ErrorMsg)
        })
        DeviceEventEmitter.addListener('getAllDevices', (Event) => {
            // alert(Event.DevicesResult + "&&" + Event.PathResult);
        });
    }

    componentDidMount() {
        const { navigation } = this.props;
        const item = JSON.parse(navigation.getParam("item"));
        const PurchaseId = navigation.getParam("PurchaseId");
        const RecId = navigation.getParam("RecId");
        this.setState({
            gooodsItem: item,
            PurchaseId: PurchaseId,
            RecId: RecId,
            operaDisable: item.PNumber == item.stocks ? true : false
        })
        KeyEvent.onKeyDownListener((evt) => {
            //监听手持机的扫码头按下等操作？
        })
        // RfidModule.getAllDevices();
        RfidModule.open();
        RfidModule.openCom();
    }

    shouldComponentUpdate(nextProps, nextState) {
        if (nextState.codesStr == this.state.codesStr && nextState.codesArr != this.state.codesArr) {
            //扫描标签即时回传过程中不调用render
            return false
        } else {
            return true
        }
    }


    _pressCode() {
        RfidModule.readRfid();
    }

    _compare() {
        if (!this.state.codesStr) {
            this._showModal("失败", "请扫描二维码")
            return
        }
        //序列号表和入库表更新  要求后端支持批量操作
        if (codesArr.length > gooodsItem.PNumber) {
            this._showModal("失败", "入库数超过采购数，请重新确认");
            this.setState({
                codesStr: '',
                codesArr: []
            })
            return;
        }
        this.setState({
            disable: true
        })
        //对比数据库已有序列号
        const { gooodsItem, codesArr } = this.state;
        const filter = 'State eq 1 and CodeType eq 1 ';
        let repeatCodes = [];
        const { token } = this.props;
        o(`erp_goodss?token=${token}`).filter(filter).get((res) => {
            if (res && res.length > 0) {
                for (let i = 0; i < res.length; i++) {
                    for (let j = 0; j < codesArr.length; j++) {
                        if (res[i].BarCode == codesArr[j]) {
                            repeatCodes.push(codesArr[j]);
                            this.setState({
                                repeatCodes: repeatCodes
                            })
                            break;
                        }
                    }
                }
            }
            this._submit()
        })
    }

    _submit() {
        const repeatCodes = this.state.repeatCodes;
        if (repeatCodes && repeatCodes.length > 0) {
            this._showConfrimModal("失败", `以下序列号正在使用中 ${repeatCodes.join(',')}`, () => { this.exclude() })
        }
        else {
            this.postData();
        }
    }

    postData() {
        const { codesArr, gooodsItem } = this.state;
        if (!codesArr || codesArr.length == 0) {
            this.setState({
                disable: false
            })
            return;
        }
        const { TenantId, UserId } = this.props.userInfo;
        const { token } = this.props;
        for (let i = 0; i < codesArr.length; i++) {
            //进库表中新增
            let params_into = {
                BarCode: codesArr[i],
                PurchaseId: gooodsItem.plist_id,
                OperatorId: UserId,
                WarehousingTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                TenantId: TenantId
            }
            //商品序列号表中新增数据
            let params = {
                BarCode: codesArr[i],
                GoodId: gooodsItem.GoodId,
                State: 1,//1正常
                TenantId: TenantId
            }
            // fetch.fetchOdata('', 'erp_intos', params_into, '', 'POST').then(res => { })
            o(`erp_intos?token=${token}`).post(params_into).save().then(res => { console.log(res) }).catch(e => { console.log(e) })
            o(`erp_goodss?token=${token}`).post(params).save().then(
                (data) => {
                    if (i == codesArr.length - 1) {
                        this.back();
                    }
                },
            ).catch(e => {
                console.log(e)
                Toast.show("入库失败", {
                    duration: Toast.durations.LONG,
                    position: Toast.positions.CENTER,
                })
            })
        }
    }
    back() {
        this._showModal("成功", "所有序列均已入库")
        this.setState({
            disable: false
        })
        const { PurchaseId, codesArr } = this.state;
        const { updatePurchaseList, navigation } = this.props;
        const param = { PurchaseId: PurchaseId, codesArr: codesArr };
        updatePurchaseList(param);
        navigation.pop(2)//back to list
    }
    exclude() {
        //排除已存在的序列号
        this._hideConfirmModal();
        const { repeatCodes, codesArr } = this.state;
        for (let i = 0; i < repeatCodes.length; i++) {
            for (let j = 0; j < codesArr.length; j++) {
                if (repeatCodes[i] == codesArr[j]) {
                    codesArr.splice(j, 1);
                    break;
                }
            }
        }
        this.setState({
            codesArr: codesArr,
            codesStr: codesArr.join(',')
        })
        this.postData();
    }
    _renderSerials(item, index, length) {
        const noBorder = index == length - 1 ? true : false;
        return (
            <SerialsItem value={item.BarCode} noBorder={noBorder} />
        )
    }

    //信息模态框
    _renderModal() {
        return (
            <MsgModal
                title={this.state.modal.title}
                msg={this.state.modal.msg}
                visible={this.state.modal.visible}
                pressBtn={() => this._hideModal()}
            />
        )
    }
    _showModal(title, msg) {
        this.setState({
            modal: {
                title: title,
                msg: msg,
                visible: true
            }
        })
    }
    _hideModal() {
        this.setState({
            modal: {
                title: '',
                msg: '',
                visible: false
            }
        })
    }

    _showConfrimModal(title, msg, confirmFuc) {
        this.setState({
            confirmModal: {
                title: title,
                msg: msg,
                visible: true,
                confirmFuc: confirmFuc
            }
        })
    }
    _hideConfirmModal() {
        this.setState({
            confirmModal: {
                title: '',
                msg: '',
                visible: false
            }
        })
    }
    //确认模态框

    _renderConfirmModal() {
        return (
            <ConfirmModal
                title={this.state.confirmModal.title}
                msg={this.state.confirmModal.msg}
                btnCancelValue={"取消入库"}
                btnConfirmValue={"自动入库"}
                visible={this.state.confirmModal.visible}
                Cancel={() => this._hideConfirmModal()}
                Confirm={this.state.confirmModal.confirmFuc}
            />
        )
    }

    _changeValue(value) {
        this.setState({
            codesStr: codesStr,
            codesArr: this.state.codesStr.split(',')
        })
    }
    _goCodeDetail() { }
    _goNoCodeDetail() { }
    _showQrCode() { }
    render() {
        let gooodsItem;
        if (this.state.gooodsItem) {
            gooodsItem = this.state.gooodsItem
        }
        const { operaDisable } = this.state;
        return (
            <ScrollView style={styles.container}>
                <View style={Style.aic}>
                    <CellTitleItem title="商品" />
                    {
                        this.state.gooodsItem ?
                            <GoodItem
                                source={gooodsItem.images[0]}
                                name={gooodsItem.Name}
                                key={gooodsItem.name}
                                showAngle={false}
                                detailList={gooodsItem.detailList}
                                pressItem={() => { return }}
                                noBorder={true}
                            /> : null
                    }
                    <View style={[Style.gap, Style.gapTop]} />
                    <IconCellItem title="有码入库量" iconName="qrcode" iconColor="#09bb07" iconSize="16" pressCode={() => this._goCodeDetail()} />
                    <IconCellItem title="无码入库量" iconName="Codepen" iconColor="#f60" iconSize="16" pressCode={() => this._goNoCodeDetail()} />
                    <IconBoxItem title="继续扫码" iconName="qrcode" iconColor="#09bb07" iconSize="25" pressCode={() => this._showQrCode()} />
                    {operaDisable ? null :
                        <View style={[{ width: Style.width }, Style.aic]}>
                            <QrCode pressCode={() => this._pressCode()} />
                            <View style={styles.textWrap}>
                                <TextInput multiline={true} placeholder="扫描添加标签" editable={false} underlineColorAndroid="transparent" style={styles.textInput} value={this.state.codesStr} ></TextInput>
                            </View>
                            <PrimaryButton title="立即入库" submit={() => this._compare()} disable={this.state.disable} />
                            <View style={styles.mt}></View>
                        </View>}

                    {
                        gooodsItem && gooodsItem.plist_into.length > 0 ?
                            <View>
                                <CellTitleItem title="已入库序列号" />
                                <View>
                                    {
                                        gooodsItem.plist_into.map((item, index) => this._renderSerials(item, index, gooodsItem.plist_into.length))
                                    }
                                </View>
                            </View> : null
                    }
                    <View style={Style.bottom}></View>
                    {this._renderModal()}
                    {this._renderConfirmModal()}
                </View>
            </ScrollView>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        width: Style.width,
        height: Style.ViewHeightD,
        backgroundColor: '#fff',
    },
    mt: {
        marginTop: 20
    },
    textWrap: {
        width: Style.width,
        height: 150,
        borderColor: '#e5e5e5',
        borderStyle: 'solid',
        borderTopWidth: 1,
        borderBottomWidth: 1,
        marginBottom: 20,

    },
    textInput: {
        padding: 10,
    },
})

export default connect(
    state => ({ userInfo: state.User.userInfo, token: state.User.token }),
    dispatch => ({
        updatePurchaseList: bindActionCreators(updatePurchaseList, dispatch),
    })
)(WareHouse)

